package jpb.Interceptor;

import jpb.constant.StatusCode;
import jpb.module.daomain.manager.Manager;
import jpb.module.service.manager.ManagerService;
import jpb.security.HandleCookie;
import jpb.security.HandleToken;
import jpb.security.ProduceJwt;
import jpb.util.DateFormatUtil;
import jpb.util.NetworkUtil;
import jpb.util.XmlUtil;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by haol on 2017/3/15.
 */
@Component
public class WebLoginInterceptor extends HandlerInterceptorAdapter {

        private ManagerService managerService;

        public WebLoginInterceptor(ManagerService managerService) {
                this.managerService = managerService;
        }

        Logger logger = LoggerFactory.getLogger(WebLoginInterceptor.class);
        HandleToken handleJWT = new HandleToken();
        private ProduceJwt produceJwt = new ProduceJwt();

        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                 Object handler) throws Exception {
                if (XmlUtil.getStrByNode("webTest").equals("yes")){
                        logger.info("用户[{}]的访问路径为-->{}", "TEST",request.getRequestURI());
                        long nowMillis = System.currentTimeMillis();
                        Date nowTime = new Date(nowMillis);
                        Manager manager = managerService.get("test");
                        String subject = handleJWT.generalSubject(manager);
                        String jwt = produceJwt.produceAppToken(StatusCode.JWT_ID, subject, StatusCode.JWT_WEB_TTL, nowTime);
                        logger.info(jwt);
                        HandleCookie.saveCookie(response, StatusCode.COOKIE_JWT_WEB, jwt);
                        managerService.updateLoginTime(manager.getId(), nowTime);

                        return true;
                }
                boolean tokenLegal;
                //logger.info("进入验证WEB Login拦截器");
                try {
                        String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
                        String mid = handleJWT.getValueByKey(token, "id");
                        logger.info("管理员[{}]的访问路径为-->{}", mid,request.getRequestURI());

                        tokenLegal = handleJWT.analyzeJWT(token);

                        if (tokenLegal) {

                                  //判断登陆时间和登陆时间一致，实现单点登陆
                                Date date = handleJWT.getIssuedAt(token);

                                Manager manager = managerService.get(mid);

                                if (date.getTime() != manager.getLoginTime().getTime()) {
                                        logger.error("管理员[{}]当前的IP地址为[{}],[{}]已在其他地方登录",manager.getAccount(),
                                                NetworkUtil.getIpAddress(request), DateFormatUtil.getYMd(new Date(manager.getLoginTime().getTime())));
                                        response.sendRedirect("/index/phoneweb/login/index.html?e=YouNeedReLogin");
                                        response.setStatus(Response.SC_UNAUTHORIZED);
                                        return false;
                                }

                                //重新成token
                                String subject = handleJWT.getSubject(token);
                                HandleCookie.updateCookie(subject, response, handleJWT.getIssuedAt(token),StatusCode.COOKIE_JWT_WEB);

                        } else {
                                response.sendRedirect("/index/phoneweb/login/index.html?e=TokenIsIegal");
                        }
                        return tokenLegal;

                } catch (NullPointerException e) {
                        response.sendRedirect("/index/phoneweb/login/index.html?e=NullPointerException");

                        logger.info("当前用户信息不存在，请重新登录");
                        response.setStatus(Response.SC_UNAUTHORIZED);
                        return false;
                }
        }
}